#include "data_struct.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>

int encode_alert_packet(ALERT_PACKET pkt, unsigned char* msg) {
	int len = 0, i;
	unsigned char* p = msg;
	memcpy(p, &pkt.timeStamp, 4);
	p += 4;
	len += 4;
	
	memcpy(p, &pkt.protocol_type, 1);
	p++;
	len++;
	
	memcpy(p, &pkt.EGP_ID, 1);
	p++;
	len++;

	memcpy(p, &pkt.port_status, 1);
	p++;
	len++;

	for(i=0; i<8; i++) {
		if(pkt.inrate_byte[i] >= 0) {
			memcpy(p, &pkt.inrate_byte[i], 2);
			p += 2;
			len += 2;

			memcpy(p, &pkt.outrate_byte[i], 2);
			p += 2;
			len += 2;

			memcpy(p, &pkt.inrate_pkt[i], 2);
			p += 2;
			len += 2;

			memcpy(p, &pkt.outrate_pkt[i], 2);
			p += 2;
			len += 2;
		}
	}

	return len;
}

void decode_alert_packet(ALERT_PACKET* pkt, unsigned char* msg) {
	unsigned char* p = msg;
	int i;
	memcpy(&pkt->timeStamp, p, 4);
	p += 4;
	
	memcpy(&pkt->protocol_type, p, 1);
	p++;
	
	memcpy(&pkt->EGP_ID, p, 1);
	p++;

	memcpy(&pkt->port_status, p, 1);
	p++;

	for(i=0; i<8; i++) {
	if((pkt->port_status & (1<<i)) != 0) {
			memcpy(&pkt->inrate_byte[i], p, 2);
			p += 2;
			memcpy(&pkt->outrate_byte[i], p, 2);
			p += 2;
			memcpy(&pkt->inrate_pkt[i], p, 2);
			p += 2;
			memcpy(&pkt->outrate_pkt[i], p, 2);
			p += 2;
		} else {
			pkt->inrate_byte[i] = -1;
			pkt->outrate_byte[i] = -1;
			pkt->inrate_pkt[i] = -1;
			pkt->outrate_pkt[i] = -1;
		}
	}
}

void print_alert_packet(ALERT_PACKET pkt) {
	int i;
	printf("protocol_type = %02x | EPG_ID = %d\n", pkt.protocol_type, pkt.EGP_ID);
	for(i=0; i<8; i++) {
		if((pkt.port_status & (1<<(7-i))) != 0) printf("1");
		else {
			printf("0");
		}
	}
	printf("\n");
	for(i=0; i<8; i++) {
		if((pkt.port_status & (1<<i)) != 0) {
			printf("port %d:\n", i);
			printf("inrate_byte = %d outrate_byte = %d\n", pkt.inrate_byte[i], pkt.outrate_byte[i]);
			printf("inrate_pkt = %d outrate_pkt = %d\n", pkt.inrate_pkt[i], pkt.outrate_pkt[i]);
		}
	}
}

void decode_atract_type_packet(ATRACT_TYPE *pkt, unsigned char* msg){
    unsigned char* p = msg;
 //   memcpy(&pkt->timeStamp, p, 4);
    p += 4;

    memcpy(&pkt->protocol_type, p, 1);
    p++;

    memcpy(&pkt->type, p, 1);
    p++;

    memcpy(&pkt->EGP_ID, p, 1);
    p += 1;
}


int encode_alert_cancel_packet(ALERT_CANCEL_PACKET pkt, unsigned char* msg) {
	int len = 0;
	unsigned char* p = msg;
    memcpy(p, &pkt.timeStamp, 4);
    p += 4;
    len += 4;
	
	memcpy(p, &pkt.protocol_type, 1);
	p++;
	len++;
	
	memcpy(p, &pkt.EGP_ID, 1);
	p++;
	len++;

    memcpy(p, &pkt.dropPackets, 4);
    p += 4;
    len += 4;

	return len;
}

void decode_alert_cancel_packet(ALERT_CANCEL_PACKET* pkt, unsigned char* msg) {
	unsigned char* p = msg;
	memcpy(&pkt->timeStamp, p, 4);
	p += 4;
	
	memcpy(&pkt->protocol_type, p, 1);
	p++;

	memcpy(&pkt->EGP_ID, p, 1);
	p++;

    memcpy(&pkt->dropPackets, p, 4);
    p += 4;
}

void print_alert_cancel_packet(ALERT_CANCEL_PACKET pkt) {
	printf("protocol_type = %02x | EGP_ID = %d\n", pkt.protocol_type, pkt.EGP_ID);
}

